/**
 * 失分区
 */
var inspectionItemCountData;
var deductBar;
/**
 * 分数分布图
 */
var scorePie;
var scorePieData = [];
/**
 * 风险等级分布图
 */
var dangerLevelPie;
var dangerLevelPieData = [];

/**
 * 整改计划完成情况
 */
var rectificationPlanPie;
var rectificationPlanPieDate = [];
var rectificationPlanBarDate;
var riskLevelChartData;

$(function() {
	onPlanChanged();
});

function onPlanChanged() {
	$.ajaxSettings.async = false;
	getAllChartDate();
//	setTimeout("initAllCharts()","6000");
	initAllCharts();
	$.ajaxSettings.async = true;
}

/**
 * 获取每个图形所需展示的数据
 * @returns
 */
function getAllChartDate() {
	var planId = document.getElementById("queryForm:selectedPlan").value;
	genScorePieDate(planId);
	genDangerLevelPieDate(planId);
	genInspectionItemCountData(planId);
	genRectificationPlanCompletion(planId);
	riskLevelChartData=JSON.parse(document.getElementById("queryForm:riskLevelChartData").value);
}

/**
 * 渲染所有图形
 * @returns
 */
function initAllCharts() {
	// 分数分布饼形图
	initScorePieChart();
	// 风险等级分布饼形图
	initDangerLevelPieChart();
	// 柱状图
	initStandardBar();
	initRectificationPlanPieChart();
	initRectificationPlanComplationBar();
	//问题等级分析柱状图
    initRiskLevelBar();
}
//问题等级分析饼图
function initRiskLevelBar(){
	if(riskLevelChartData!=null&&riskLevelChartData.length>0){
		$("#riskLevelBar").html("");
		var xAxisData=[];
	    var yAxisData={"一级":[],"二级":[],"三级":[],"四级":[]};//{"一级":[],}
		for(var i in riskLevelChartData){
			xAxisData.push(riskLevelChartData[i]["name"]);
			yAxisData["一级"].push(riskLevelChartData[i]["levelOneCount"]);
			yAxisData["二级"].push(riskLevelChartData[i]["levelTwoCount"]);
			yAxisData["三级"].push(riskLevelChartData[i]["levelThreeCount"]);
			yAxisData["四级"].push(riskLevelChartData[i]["levelFourCount"]);
		}
		var yDataList=[];
		for(var key in yAxisData){
			yDataList.push({lineName:key,lineValue:yAxisData[key]});
		}
		var data = {
				xData:{
					value:xAxisData
				},
				yData:{
					name:'数量',
					value:yDataList
				}
		};
		var bar =new CategoryBar("riskLevelBar");
		 bar.setData(data);
		 bar.setDataZoom(true).setDataView(false).setZoomTool(false).setRestore(false).setMagicType(false);
		 bar.show();
	}else{
		$("#riskLevelBar").html("暂无数据");
	}
	
}

/**
 * 生成分数分布图的数据，即每个得分区间内的变电站个数
 */
function genScorePieDate(planId) {
	$.getJSON('/rest/assessment/getStationCountInScoreRange/' + planId, function(result) {
		scorePieData = [];
		for(var i in result) {
			var obj = result[i];
			var range = "["+obj.min+","+obj.max+"]";
			scorePieData.push([range,obj.count]);
		}
	});
}

/**
 * 渲染分数分布饼形图
 */
function initScorePieChart() {
	if(scorePieData.length == 0) {
		$("#scoreDistribution").html("暂无数据信息");
	} else {
		scorePie = new Pie("scoreDistribution");
		scorePie.setPie(scorePieData).setPieCenter('55%', '55%');
		var option = scorePie.getOption();
		option.grid.top=80;
		option.title.textStyle.fontSize = 16;
		option.title.textStyle.fontWeight = 'normal';
	//	option.legend.top = 'center';
	//	option.legend.right = '70%';
		option.legend.orient = 'vertical';
		option.series[0].label.normal.formatter="{b}:{c}";
		option.series[0].label.normal.formatter="{c} ({d}%)";
		option.series[0].radius="60%";
		option.tooltip.formatter="分值范围：{b} <br/> 变电站数量：{c}个 ({d}%)";
		
		scorePie.setPieOuterRadius('50%')
		.setLegendPosition('left', 'center')
		.setTitlePosition('center');
		
		scorePie.show();
	}
}

/**
 * 生成风险等级饼形图数据
 * @returns
 */
function genDangerLevelPieDate(planId) {
	$.getJSON('/rest/assessment/getDangerLevelDistribute/' + planId, function(result) {
		dangerLevelPieData = [];
		for(var i in result) {
			var obj = result[i];
			dangerLevelPieData.push([obj.dangerLevel,obj.count]);
		}
	});
}

/**
 * 渲染问题设备分布图
 */
function initDangerLevelPieChart() {
	if(dangerLevelPieData.length == 0) {
		$("#dangerlevelDistribution").html("暂无数据信息");
	} else {
		dangerLevelPie = new Pie("dangerlevelDistribution");
		dangerLevelPie.setPie(dangerLevelPieData).setPieCenter('55%', '55%');
		var option = dangerLevelPie.getOption();
		option.grid.top=80;
		option.title.textStyle.fontSize = 16;
		option.title.textStyle.fontWeight = 'normal';
	//	option.legend.top = 'center';
	//	option.legend.right = '70%';
		option.legend.orient = 'vertical';
		option.series[0].label.normal.formatter="{b}:{c}";
		option.series[0].label.normal.formatter="{c} ({d}%)";
		option.series[0].radius="60%";
		option.tooltip.formatter="风险等级：{b} <br/> 问题设备数量：{c}个  ({d}%)";
		
		dangerLevelPie.setPieOuterRadius('50%')
			.setLegendPosition('left', 'center')
			.setTitlePosition('center');
		
		dangerLevelPie.show();
	}
}

/**
 * 评价项目扣分项
 * @returns
 */
function initStandardBar() {
	var xData = [];
	var yData = [];
	for (var i in inspectionItemCountData) {
		var obj = inspectionItemCountData[i];
		xData.push(obj.itemName);
		yData.push(obj.count);
	}
	if(xData.length == 0) {
		$("#deductBar").html("暂无数据信息");
	} else {
		deductBar = new CategoryBar("deductBar");
		var option = {
				color: ['#3398DB'],
				tooltip : {
					trigger: 'axis',
					axisPointer : {            // 坐标轴指示器，坐标轴触发有效
						type : 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
						axisLabel : {
							formatter : function(value) {
								return value.split("").join("\n");
							}
						}
					}
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true
				},
				xAxis : [
					{
						type : 'category',
						data : xData,
						axisTick: {
							alignWithLabel: true
						},
						axisLabel : {
							interval : 0,
							rotate : 0,
							textStyle : {
								color : '#737373'
							},
							formatter : function(value) {
								return value;
							}
						}
					}
					],
					yAxis : [
						{
							type : 'value',
							name : '个数'
						}
						],
						toolbox: {
							show : true,
							feature : {
								dataView : {
									readOnly: true,
									optionToContent:function(opt){
										var series = opt.series;
										var table = '<table border="1" style="width:100%;font-size:14px;font-family: sans-serif"><tbody><tr>'
											+ '<td style="width:85%;">评价项目</td>' ;
										for(var j=0;j<series.length;j++){
											if(series[j].name){
												table = table + '<td style="width:15%;">' + series[j].name + '</td>';// 行名称：扣分变电站个数
											}else{
												table = table + '<td>'+" "+'</td>';
											}
										}
										for (var i = 0, l = xData.length; i < l; i++) {
											table += '<tr>' + '<td style="text-align:left">' + xData[i] + '</td>';
											if(isNaN(parseInt(yData[i]))) {
												table = table + '<td>' + '</td>';
											} else {
												table = table + '<td>' + yData[i] + '</td>';
											}
										}
										table += '</tbody></table>';
										return table;
									},
								},
								magicType: {show: true, type: ['line', 'bar']},
								restore : {show: true},
								saveAsImage : {
									show: true,
									iconStyle : {
										normal : {},
										emphasis : {}
									}
								}
							}
						},
						dataZoom: [
							{
								type: 'inside',
								startValue:0,
								endValue:14
							}
							],
							series : [
								{
									name:'扣分变电站个数',
									type:'bar',
									barWidth: '60%',
									data:yData,
									markPoint: {
										data: [
											{type: 'max', name: '最大值'},
											{type: 'min', name: '最小值'}
											]
									},
									markLine: {
										data: [
											{type: 'average', name: '平均值'}
											]
									}
								}
								]
		};
		deductBar.setOption(option);
		deductBar.show();
	}
}

/**
 * 评价项目扣分次数
 * @param planId
 * @returns
 */
function genInspectionItemCountData(planId) {
	$.getJSON('/rest/assessment/getInspectionItemCount/' + planId, function(result) {
		inspectionItemCountData = result;
	});
}

$('#li1 a').click(function (e) {
	e.preventDefault();
	$(this).tab('show');
	initScorePieChart();
});
$('#li2 a').click(function (e) {
	e.preventDefault();
	$(this).tab('show');
	initDangerLevelPieChart();
	initStandardBar();
});
$('#li3 a').click(function (e) {
	e.preventDefault();
	$(this).tab('show');
	initRectificationPlanPieChart();
	initRectificationPlanComplationBar();
});
$("#li0 a").click(function(e){
	e.preventDefault();
	$(this).tab('show');
	//问题等级分析柱状图
    initRiskLevelBar();
});
/**
 * 获取指定计划的每个变电站的完成率数据
 * @returns
 */
function getStationComplateDate() {
	$.ajaxSettings.async = false;
	var stationComplateRatioData = [];
	var planId = document.getElementById("queryForm:selectedPlan").value;
	$.getJSON('/rest/assessment/getStationComplateRatio/' + planId, function(result) {
		stationComplateRatioData = result;
	});
	createStationDIVByPlan(stationComplateRatioData);
	$.ajaxSettings.async = true;
}

/**
 * 将每个变电站的完成率数据添加到页面显示中
 * @returns
 */
function createStationDIVByPlan(stationComplateRatioData) {
	$("#pDiv").empty();
	for(var i=0; i<stationComplateRatioData.length;i++) {
		var obj = stationComplateRatioData[i];
		var groupDiv = document.createElement("div");
		groupDiv.className = "progress-group";
		
		var innerHTML = "<span class='progress-text'>" + obj.stationName + "</span>"
			+ "<span class='progress-number'><b>" + obj.itemsNumFinished + "</b>/" + obj.itemsNumAll + "</span>"
			+ "<div class='progress sm'>"
			+ "<div class='progress-bar progress-bar-aqua' style='width: " + obj.finishRatio + "%'></div></div>";
		
		groupDiv.innerHTML = innerHTML;
		document.getElementById('pDiv').appendChild(groupDiv);
	}
}

/**
 * 整改计划完成情况——根据问题类别进行统计
 * @param planId
 * @returns
 */
function genRectificationPlanCompletion(planId) {
	$.getJSON('/rest/assessment/getRectificationPlanCompletion/' + planId, function(result) {
		rectificationPlanBarDate = result;
		rectificationPlanPieDate = [];
		for(var i in result) {
			var obj = result[i];
			rectificationPlanPieDate.push([obj.type,obj.unnfinishCount+obj.finishCount]);
		}
	});
}

/**
 * 渲染整改计划完成情况统计图
 * @returns
 */
function initRectificationPlanPieChart() {
	if(rectificationPlanPieDate.length == 0) {
		$("#questionType").html("暂无数据信息");
	} else {
		rectificationPlanPie = new Pie("questionType");
		rectificationPlanPie.setPie(rectificationPlanPieDate).setPieCenter('55%', '55%');
		var option = rectificationPlanPie.getOption();
		option.grid.top=80;
		option.title.textStyle.fontSize = 16;
		option.title.textStyle.fontWeight = 'normal';
	//	option.legend.top = 'center';
	//	option.legend.right = '70%';
		option.legend.orient = 'vertical';
		option.series[0].label.normal.formatter="{b}:{c}";
		option.series[0].label.normal.formatter="{c} ({d}%)";
		option.series[0].radius="60%";
		option.tooltip.formatter="{b} <br/> 整改计划：{c}个  ({d}%)";
		
		rectificationPlanPie.setPieOuterRadius('50%')
			.setLegendPosition('left', 'center')
			.setTitlePosition('center');
		
		rectificationPlanPie.show();
	}
}

/**
 * 渲染不同类型的整改计划的完成情况
 * @returns
 */
function initRectificationPlanComplationBar() {
	var linebars = new Bars("questionTypeBar");
	if(typeof(rectificationPlanBarDate) == "undefined") {
		$("#questionTypeBar").html("该时间暂无数据信息");
	} else {
		var types = [];
		var unfinish = [];
		var finish = [];
		var sums = [];
		for (var i in rectificationPlanBarDate) {
			types.push(rectificationPlanBarDate[i].type);
			unfinish.push(rectificationPlanBarDate[i].unnfinishCount);
			finish.push(rectificationPlanBarDate[i].finishCount);
		}
		// 完成率
		var ratios = [];
		for ( var i = 0; types.length > i; i++) {
			var sum = unfinish[i]+finish[i];
			sums.push(sum);
			if(0 == sum) {
				ratios.push(0);
			} else {
				var ratio = (parseInt(finish[i]) / parseInt(sum))*100;
				ratios.push(ratio.toFixed(2));
			}
		}
		linebars.setRatio(ratios);
		linebars.setMeasures(unfinish);
		linebars.setComplete(finish);
		linebars.setXdatas(types);
		linebars.show();
	}
}

var Bars = function(chartid) {
	var colors = [ '#5793f3', '#008B8B', '#675bba' ];
	var myChart = echarts.init(document.getElementById(chartid));
	var option = {
		dataZoom : [ {
			id : 'dataZoomX',
			type : 'inside',
			show : true,
			xAxisIndex : [ 0 ],
			filterMode : 'filter'
		} ],
		title : {},
		tooltip : {
			trigger : 'axis'
		},
		toolbox : {
			feature : {
				dataView : {
					readOnly : false,
					  show: true,
					optionToContent : function(opt) {
						var axisData = opt.xAxis[0].data;
						var series = opt.series;
						var table = '<table border="1" style="width:100%;text-align:center"><tbody><tr>'
								+ '<td>' + opt.xAxis[0].name + '</td>';
						for ( var j = 0; j < series.length; j++) {
							table = table + '<td>' + series[j].name + '</td>';
						}
						for ( var i = 0, l = axisData.length; i < l; i++) {
							table += '<tr>' + '<td>' + axisData[i] + '</td>';
							for ( var z = 0; z < series.length; z++) {
								if (isNaN(parseInt(series[z].data[i]))) {
									table = table + '<td>' + '</td>';
								} else {
									table = table + '<td>' + series[z].data[i]
											+ '</td>';
								}
							}
						}
						table += '</tbody></table>';
						return table;
					},
					iconStyle : {
						normal : {},
						emphasis : {}
					}
				},
				restore : {
					show : true
				},
				saveAsImage : {
					show : true
				}
			}
		},
		grid : {
			containLabel : true
		},
		legend : {
			data : ['整改计划完成率','未完成','已完成']
		},
		xAxis : [ {
			type : 'category',
			axisTick : {
				alignWithLabel : true
			},
			data : []
		} ],
		yAxis : [ {
			type : 'value',
			name : '整改计划完成率',
			min : 0,
			max : 100,
			position : 'right',
			axisLabel : {
				formatter : '{value}%'
			}
		}, {
			type : 'value',
			name : '数量',
			min : 0,
			
			position : 'left'
		} ],
		series : [ {
			name : '整改计划完成率',
			type : 'line',
			data : []
		}, {
			name : '未完成',
			type : 'bar',
			yAxisIndex : 1,
			data : [],
			label:{
				normal:{
					show:true,
					textStyle:{},
					position:'top'
				},
				emphasis:{
					show:true,
					textStyle:{}
				}
			},
			 itemStyle:{
                 normal:{color:'#7ECF51'}
             }
		}, {
			name : '已完成',
			type : 'bar',
			yAxisIndex : 1,
			data : [],
			label:{
				normal:{
					show:true,
					textStyle:{},
					position:'top'
				},
				emphasis:{
					show:true,
					textStyle:{}
				}
			},
			 itemStyle:{
                 normal:{color:'#6495ED'}
             }
		} ]
	};
	this.show = function() {
		myChart.setOption(option);
	};
	this.getChart = function() {
		return myChart;
	};
	this.setRatio = function(datas) {
		option.series[0].data = datas;
	};
	this.setMeasures = function(datas) {
		option.series[1].data = datas;
	};
	this.setComplete = function(datas) {
		option.series[2].data = datas;
	};
	this.setXdatas = function(datas) {
		option.xAxis[0].data = datas;
	};
};